<template>
  <el-row>
    <el-col :span="4" style="border-right: #EDEDED 1px solid; height:calc(100vh - 176px) ;">
      <el-tree :data="deptTree"
               :props="treeProps"
               node-key="id"
               :default-expand-all="true"
               icon-class="el-icon-caret-right"
               :highlight-current="true"
               @node-click="selectDept">
        <template #default="{ node }">
          <i v-if="node.isLeaf" class="el-icon-arrow-right"></i>
          <span>{{ node.label }}</span>
        </template>
      </el-tree>
    </el-col>
    <el-col :span="20" style="padding-left: 10px;">
      <el-space wrap>
        <el-button type="primary" @click="add" size="medium">
          <el-icon :size="14">
            <plus />
          </el-icon>
          添加
        </el-button>
        <el-upload :show-file-list="false"
           accept=".xls,.xlsx"
           :auto-upload="false"
           :multiple="false"
           :on-change="importData"
           :action="actionUrl">
          <el-button type="info" size="medium">
            <el-icon :size="14">
              <upload-filled />
            </el-icon>
            批量上传
          </el-button>
          <!--<el-divider direction="vertical"></el-divider>-->
          <!--<el-link type="success">下载模板</el-link>-->
        </el-upload>
      </el-space>
      <el-divider />
      <el-table :data="employees" style="width: 100%">
        <el-table-column prop="name" label="姓名" width="120" />
        <el-table-column label="性别" width="80">
          <template #default="scope">
            {{ scope.row.gender === 1 ? '男' : '女' }}
          </template>
        </el-table-column>
        <el-table-column label="年龄" prop="age" width="80" />
        <el-table-column label="政治面貌" prop="politic" width="200" />
        <el-table-column label="籍贯" prop="nativePlace" width="120" />
        <el-table-column label="民族" prop="ethic" width="120" />
        <el-table-column label="电话号码" prop="phone" width="120" />
        <el-table-column prop="idCard" label="身份证号" width="200" />
        <el-table-column label="操作">
          <template #default="scope">
            <el-button type="text" size="small" @click="edit(scope.row)">编辑</el-button>
            <!--<el-button type="text" size="small" @click="del(scope.row)">删除</el-button>-->
          </template>
        </el-table-column>
      </el-table>
    </el-col>
  </el-row>
  <!--用户信息编辑对话框-->
  <el-dialog v-model="dialogVisible" title="员工信息" width="60%" @open="clearValidate" @closed="resetForm">
    <div class="dlgContainer">
      <el-form ref="empForm" :model="employeeInfo" :rules="employeeRules" label-width="100px">
        <el-row>
          <el-col :span="20">
            <el-row>
              <el-col :span="6">
                <el-form-item label="姓名" prop="name">
                  <el-input v-model="employeeInfo.name" placeholder="请输入姓名"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="身份证号" prop="idCard">
                  <el-input v-model="employeeInfo.idCard" placeholder="请输入身份证号"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="民族" prop="ethic">
                  <el-select v-model="employeeInfo.ethic" placeholder="请选择民族">
                    <el-option v-for="ethic in dics.ethics" :label="ethic.name" :value="ethic.name" :key="ethic.value" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="籍贯" prop="nativePlace">
                  <el-select v-model="employeeInfo.nativePlace" placeholder="请选择籍贯">
                    <el-option v-for="province in dics.provinces" :label="province.name" :value="province.name" :key="province.value" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="6">
                <el-form-item label="健康状况" prop="healthy">
                  <el-select v-model="employeeInfo.healthy" placeholder="请选择健康状况">
                    <el-option v-for="healthy in dics.healtyTypes" :label="healthy.name" :value="healthy.name" :key="healthy.value" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="政治面貌" prop="politic">
                  <el-select v-model="employeeInfo.politic" placeholder="请选择政治面貌">
                    <el-option v-for="politic in dics.politics" :label="politic.name" :value="politic.name" :key="politic.value" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="电话" prop="phone">
                  <el-input v-model="employeeInfo.phone" placeholder="请输入电话号码"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="婚姻状况" prop="maritalStatus">
                  <el-select v-model="employeeInfo.maritalStatus" placeholder="请选择婚姻状况">
                    <el-option v-for="ms in dics.maritalStatus" :label="ms.name" :value="ms.name" :key="ms.value" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="6">
                <el-form-item label="所属部门" prop="departId">
                  <el-select v-model="employeeInfo.departId" placeholder="请选择所属部门">
                    <el-option v-for="item in deptTree[0].children" :key="item.id" :label="item.name" :value="item.id">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="职务" prop="post">
                  <el-input v-model="employeeInfo.post"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="职位" prop="position">
                  <el-input v-model="employeeInfo.position"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="人员类型" prop="roleType">
                  <el-select v-model="employeeInfo.roleType" placeholder="请选择人员类型">
                    <el-option v-for="rt in dics.roleTypes" :label="rt.name" :value="rt.name" :key="rt.value" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
          </el-col>
          <el-col :span="4">
            <div class="imgContainer">
              <el-image>
                <template #error>
                  <div class="image-slot">
                    <el-upload class="avatar-uploader"
                               :show-file-list="false"
                               accept="image/jpeg,image/png,image/jpg"
                               :auto-upload="false"
                               :multiple="false"
                               :on-change="selectImg"
                               :action="actionUrl">
                      <img v-if="employeeInfo.avatar" :src="employeeInfo.avatar" class="avatar">
                      <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                    </el-upload>
                  </div>
                </template>
              </el-image>
            </div>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="15">
            <el-form-item label="家庭住址" prop="address">
              <el-input v-model="employeeInfo.address" placeholder="请输入家庭住址"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="9">
            <el-form-item label="电子邮箱" prop="email">
              <el-input v-model="employeeInfo.email" placeholder="请输入电子邮箱"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <!--<el-form-item label="照片" prop="picUrl">-->
        <!--  <el-input v-model="employeeInfo.picUrl" placeholder="请输入照片地址"></el-input>-->
        <!--</el-form-item>-->
        <el-row>
          <el-col :span="8">
            <el-form-item label="合同类型" prop="contactType">
              <el-select v-model="employeeInfo.contactType" placeholder="请选择合同类型">
                <el-option v-for="ct in dics.contactTypes" :label="ct.name" :value="ct.name" :key="ct.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="合同开始日期" prop="contactStart" label-width="120">
              <el-date-picker v-model="employeeInfo.contactStart" type="date" placeholder="请选择合同开始日期"></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="合同期限" prop="contactPeriod">
              <el-select v-model="employeeInfo.contactPeriod" placeholder="请选择合同期限">
                <el-option v-for="cp in dics.contactPeriods" :label="cp.name" :value="cp.name" :key="cp.value" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-collapse>
          <el-collapse-item name="1">
            <template #title>
              教育经历<i class="header-icon el-icon-s-management"></i>
            </template>
            <el-row>
              <el-col :span="4">
                <el-form-item label="第一学历">
                  <el-select v-model="employeeInfo.firstEduExp" placeholder="请选择第一学历">
                    <el-option v-for="ee in dics.eduExps" :label="ee.name" :value="ee.name" :key="ee.value" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="4">
                <el-form-item label="第一学位">
                  <el-select v-model="employeeInfo.firstDegree" placeholder="请选择第一学位">
                    <el-option v-for="ed in dics.eduDegrees" :label="ed.name" :value="ed.name" :key="ed.value" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="毕业学校">
                  <el-input placeholder="请填写毕业学校" v-model="employeeInfo.firstSchool"/>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="所学专业">
                  <el-input placeholder="请填写所学专业" v-model="employeeInfo.firstMajor"/>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="4">
                <el-form-item label="最高学历">
                  <el-select v-model="employeeInfo.lastEduExp" placeholder="请选择最高学历">
                    <el-option v-for="ee in dics.eduExps" :label="ee.name" :value="ee.name" :key="ee.value" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="4">
                <el-form-item label="最高学位">
                  <el-select v-model="employeeInfo.lastDegree" placeholder="请选择最高学位">
                    <el-option v-for="ed in dics.eduDegrees" :label="ed.name" :value="ed.name" :key="ed.value" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="毕业学校">
                  <el-input placeholder="请填写毕业学校" v-model="employeeInfo.lastSchool"/>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="所学专业">
                  <el-input placeholder="请填写所学专业" v-model="employeeInfo.lastMajor"/>
                </el-form-item>
              </el-col>
            </el-row>
          </el-collapse-item>
          <el-collapse-item name="2">
            <template #title>
              培训经历<i class="header-icon el-icon-s-order"></i>
            </template>
            <el-form-item label-width="0">
              <el-input type="textarea" placeholder="请填写培训经历" v-model="employeeInfo.trainExp" maxlength="255" show-word-limit/>
            </el-form-item>
          </el-collapse-item>
          <el-collapse-item name="3">
            <template #title>
              备注说明<i class="header-icon el-icon-info"></i>
            </template>
            <el-form-item label-width="0">
              <el-input v-model="employeeInfo.remark" type="textarea" maxlength="200" placeholder="请输入说明" show-word-limit></el-input>
            </el-form-item>
          </el-collapse-item>
        </el-collapse>
      </el-form>

    </div>
    <template #footer>
      <el-row justify="space-between">
        <el-col :span="6" style="text-align: left;">
          <!--<el-button @click="resetForm">取消</el-button>-->
        </el-col>
        <el-col :span="6">
          <el-button type="info" v-show="dialogStatus==0">重置</el-button>
          <el-button type="danger" @click="del" v-show="dialogStatus==1">删除</el-button>
          <el-button type="primary" @click="submitForm">保存员工信息</el-button>
        </el-col>
      </el-row>
    </template>
  </el-dialog>
</template>

<script>
import {
  deleteEmp,
  list,
  save,
  importDataFromExcel,
  getDics,
  newEmployee,
  empExcelHeaders,
  uploadEmployees
} from "@/api/employee";
import {ElMessage, ElMessageBox} from "element-plus";
import {employeeRules} from "@/api/rules";
import config from "@/config/config";
import {getBase64} from "@/util/util";
import {Plus, UploadFilled} from "@element-plus/icons-vue";

export default {
  name: "Employee",
  components: {UploadFilled, Plus},
  setup() {
    // 部门树属性
    const treeProps = {
      children: 'children',
      label: 'name',
    }
    // 上传地址
    const uploadUrl = `${config.server}/employee/upload/photo`

    return {
      treeProps,
      newEmployee,
      employeeRules,
      uploadUrl,
      getBase64,
      empExcelHeaders,
      getDics
    }
  },
  data() {
    return {
      employees: [],
      deptTree: [
        {
          id: 0,
          name: '全部',
          icon: 'el-icon-school',
          children: [],
        }
      ],
      page: { current: 1, size: 10 },
      departId: 0,
      dialogVisible: false,
      dialogStatus: 0,
      employeeInfo: this.newEmployee,
      actionUrl: 'abc',
      dics: {}
    }
  },
  created() {
    // 获取数据字典
    this.getDics().then(res => {
      this.dics = res
      this.deptTree[0].children = res.departs
      // 获取员工列表
      this.getEmployees()
    })
  },
  methods: {
    // 获取员工列表
    getEmployees() {
      list(this.departId, this.page.current, this.page.size).then(res => {
        this.employees = res.data.records
        this.page.current = res.data.current
        this.page.size = res.data.size
      })
    },
    // 选择部门
    selectDept(data) {
      this.departId = data.id
      this.getEmployees()
    },
    // 添加员工
    add() {
      this.employeeInfo = JSON.parse(JSON.stringify(this.newEmployee))
      this.employeeInfo.departId = this.departId || ''
      this.dialogVisible = true
      this.dialogStatus = 0
    },
    // 编辑员工
    edit(row) {
      this.employeeInfo = JSON.parse(JSON.stringify(row))
      this.dialogVisible = true
      this.dialogStatus = 1
    },
    // 删除员工
    del() {
      let row = this.employeeInfo
      ElMessageBox.confirm('你正在删除用户信息. 是否继续?', '警告',{
          confirmButtonText: '删除',
          cancelButtonText: '取消',
          type: 'warning',
        }).then(() => {
          deleteEmp(row.id).then(res => {
            ElMessage.success('删除成功')
            this.dialogVisible = false
            this.getEmployees()
          })
        }).catch(() => {
          ElMessage.info('取消删除')
      })
    },
    // 提交表单
    submitForm() {
      this.$refs['empForm'].validate((valid) => {
        if(valid) {
          ElMessageBox.confirm(
              '确定要保存该用户信息?',
              '提示',
              {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                type: 'warning',
              }
          ).then(() => {
            save(this.employeeInfo).then(res => {
              if(res.code === 200) {
                ElMessage.success(res.msg)
                this.getEmployees()
                this.resetForm()
              }
              else {
                ElMessage.error(res.msg)
              }
            })
          }).catch(() => {
            ElMessage.info('保存取消')
          })
        }
      })
    },
    // 重置表单
    resetForm() {
      this.$refs['empForm'].resetFields()
      this.dialogVisible = false
    },
    // 清除验证信息
    clearValidate() {
      let _form = this.$refs['empForm']
      if(_form) {
        _form.clearValidate()
        _form.resetFields()
      }
    },
    // 选择头像
    selectImg(file) {
      const isIMAGE = file.type === 'image/jpeg' || 'image/jpg' || 'image/png'  // 限制图片格式
      const isLt1M = file.size / 1024 / 1024 * 20 < 1 // 限制图片大小
      if (!isIMAGE) {
        this.$message.error('上传文件只能是图片格式!')
        return
      }
      if (!isLt1M) {
        this.$message.error('上传文件大小不能超过 50KB!')
        return
      }
      if(isIMAGE && isLt1M) {
        getBase64(file.raw, txt => {
          this.employeeInfo.avatar = txt
        })
      }
    },
    // 导入数据
    importData(file){
      // 将excel表的数据转换成json格式
      importDataFromExcel(file, this.dics).then(list => {
        uploadEmployees(list).then(res => {
          ElMessage.success(res.msg)  // 显示结果信息
          this.getEmployees() // 刷新列表
        })
      }).catch(e => {
        ElMessage.error(e)
      })
    }
  }
}
</script>

<style scoped>
  .dlgContainer {
    padding: 0px 40px;
  }
  .imgContainer {
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: right;
    /*border: 1px solid red;*/
  }
  .avatar-uploader {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader:hover {
    border-color: #409eff;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 148px;
    height: 168px;
    line-height: 168px;
    text-align: center;
  }
  .avatar {
    width: 148px;
    height: 168px;
    display: block;
  }
</style>